/**
 防抖方法处理
 @param fn 被处理的方法
 @param delay 防抖延迟时间
 @param leading 首次是否执行方法
 **/
function debounce(fn,delay,leading){
    var timer = null;
    leading = leading || false;
    delay = delay || 500;
    var handleFn = function(){
        //通过 Promise 抛出返回值
        return new Promise((resovle,reject)=>{
            if(timer) clearTimeout(timer);
            //获取this和argument
            var _this = this
            var _arguments = arguments

            if(leading){
                //通过一个变量来记录是否立即执行
                var isInvoke = false;
                if(!timer){
                    resovle(fn.apply(_this,_arguments))
                    isInvoke = true
                }

                timer = setTimeout(function(){
                    //让下次可以再次执行
                    timer = null;
                    //如果只输入了一次 则防止重复不执行了
                    if(!isInvoke){
                        resovle(fn.apply(_this,_arguments))
                    }
                },delay)
            }else{
                timer = setTimeout(function(){
                    //在执行时，通过apply来使用_this和arguments
                    resovle(fn.apply(_this,_arguments))
                },delay);
            }
        })

    }

    //取消处理
    handleFn.cancel = function(){
        if(timer) clearTimeout(timer)
    }

    return handleFn;
}

var isPhone = function() {
    return ! /ifr/.test(document.body.className) && document.body.clientWidth <= ($.maxPhoneW || 720) && 0 < document.body.clientWidth
}

//获取浏览器参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
    var r = window.location.search.substr(1).match(reg);
    if (r!=null) return (r[2]); return null;
}

//获取所有的表情图片关联信息
var ba = function() {
    var a = {
        "[\u5fae\u7b11]": "2009426204649332.gif",
        "[\u6487\u5634]": "2009426204432159.gif",
        "[\u8272]": "2009426203942933.gif",
        "[\u53d1\u5446]": "2009426203927717.gif",
        "[\u5f97\u610f]": "2009426204332318.gif",
        "[\u6d41\u6cea]": "2009426204655335.gif",
        "[\u5bb3\u7f9e]": "2009426204421181.gif",
        "[\u95ed\u5634]": "2009426203947115.gif",
        "[\u7761]": "200942620473854.gif",
        "[\u5927\u54ed]": "2009426204336398.gif",
        "[\u5c34\u5c2c]": "200942620363243.gif",
        "[\u53d1\u6012]": "2009426204453127.gif",
        "[\u8c03\u76ae]": "2009426203918413.gif",
        "[\u5472\u7259]": "2009426203834799.gif",
        "[\u60ca\u8bb6]": "2009426204438161.gif",
        "[\u96be\u8fc7]": "2009426204457207.gif",
        "[\u9177]": "2009426203631924.gif",
        "[\u51b7\u6c57]": "2009426203826955.gif",
        "[\u6293\u72c2]": "2009426204343825.gif",
        "[\u5410]": "2009426204710696.gif",
        "[\u5077\u7b11]": "2009426203535123.gif",
        "[\u6109\u5feb]": "2009426203845213.gif",
        "[\u767d\u773c]": "2009426204559431.gif",
        "[\u50b2\u6162]": "2009426203626168.gif",
        "[\u9965\u997f]": "200942620382405.gif",
        "[\u56f0]": "2009426204511756.gif",
        "[\u60ca\u6050]": "200942620476841.gif",
        "[\u6d41\u6c57]": "2009426203612485.gif",
        "[\u61a8\u7b11]": "2009426204554209.gif",
        "[\u60a0\u95f2]": "2009426204725241.gif",
        "[\u594b\u6597]": "2009426203552327.gif",
        "[\u5492\u9a82]": "2009426203643426.gif",
        "[\u7591\u95ee]": "2009426204716110.gif",
        "[\u5618]": "2009426204121698.gif",
        "[\u6655]": "2009426203543362.gif",
        "[\u75af\u4e86]": "200942620387292.gif",
        "[\u8870]": "200942620463342.gif",
        "[\u9ab7\u9ac5]": "2009426204614878.gif",
        "[\u6572\u6253]": "2009426204353991.gif",
        "[\u518d\u89c1]": "2009426203520915.gif",
        "[\u64e6\u6c57]": "200942620400917.gif",
        "[\u62a0\u9f3b]": "2009426203524599.gif",
        "[\u9f13\u638c]": "2009426203744593.gif",
        "[\u7cd7\u5927\u4e86]": "2009426204347115.gif",
        "[\u574f\u7b11]": "2009426203640891.gif",
        "[\u5de6\u54fc\u54fc]": "2009426204611216.gif",
        "[\u53f3\u54fc\u54fc]": "2009426203823435.gif",
        "[\u54c8\u6b20]": "2009426204626462.gif",
        "[\u9119\u89c6]": "2009426204413198.gif",
        "[\u59d4\u5c48]": "2009426204519320.gif",
        "[\u5feb\u54ed\u4e86]": "2009426204634617.gif",
        "[\u9634\u9669]": "200942620370827.gif",
        "[\u4eb2\u4eb2]": "2009426204719604.gif",
        "[\u5413]": "2009426204623279.gif",
        "[\u53ef\u601c]": "200942620415695.gif",
        "[\u83dc\u5200]": "2009426203922939.gif",
        "[\u897f\u74dc]": "2009426203856297.gif",
        "[\u5564\u9152]": "2009426204630345.gif",
        "[\u7bee\u7403]": "2009426204326116.gif",
        "[\u4e52\u4e53]": "2009426203723341.gif",
        "[\u5496\u5561]": "2009426204523765.gif",
        "[\u996d]": "2009426203556965.gif",
        "[\u732a\u5934]": "2009426203837308.gif",
        "[\u73ab\u7470]": "2009426203656691.gif",
        "[\u51cb\u8c22]": "2009426204619707.gif",
        "[\u5634\u5507]": "200942620410615.gif",
        "[\u7231\u5fc3]": "2009426203954405.gif",
        "[\u5fc3\u788e]": "2009426203619609.gif",
        "[\u86cb\u7cd5]": "200942620408116.gif",
        "[\u95ea\u7535]": "2009426203647674.gif",
        "[\u70b8\u5f39]": "2009426204329724.gif",
        "[\u5200]": "2009426204551293.gif",
        "[\u8db3\u7403]": "2009426203714788.gif",
        "[\u74e2\u866b]": "2009426203740796.gif",
        "[\u4fbf\u4fbf]": "2009426204731691.gif",
        "[\u6708\u4eae]": "2009426204640960.gif",
        "[\u592a\u9633]": "2009426203720577.gif",
        "[\u793c\u7269]": "2009426203930309.gif",
        "[\u62e5\u62b1]": "2009426204417246.gif",
        "[\u5f3a]": "200942620450530.gif",
        "[\u5f31]": "2009426204112537.gif",
        "[\u63e1\u624b]": "2009426203539512.gif",
        "[\u80dc\u5229]": "2009426204646794.gif",
        "[\u62b1\u62f3]": "2009426204728451.gif",
        "[\u52fe\u5f15]": "2009426203737612.gif",
        "[\u62f3\u5934]": "2009426203910315.gif",
        "[\u5dee\u52b2]": "200942620367378.gif",
        "[\u7231\u4f60]": "2009426203528732.gif",
        "[NO]": "2009426204721695.gif",
        "[OK]": "200942620396799.gif",
        "[\u7231\u60c5]": "2009426205315887.gif",
        "[\u98de\u543b]": "2009426205314448.gif",
        "[\u8df3\u8df3]": "2009426203559585.gif",
        "[\u53d1\u6296]": "2009426205315218.gif",
        "[\u6004\u706b]": "2009426205315310.gif",
        "[\u8f6c\u5708]": "2009426205315736.gif",
        "[\u78d5\u5934]": "2009426204734202.gif",
        "[\u56de\u5934]": "2009426205315546.gif",
        "[\u8df3\u7ef3]": "2009426205315951.gif",
        "[\u6295\u964d]": "2009426205315383.gif",
        "[\u6fc0\u52a8]": "2009426205315324.gif",
        "[\u4e71\u821e]": "2009426205315991.gif",
        "[\u732e\u543b]": "2009426205315888.gif",
        "[\u5de6\u592a\u6781]": "2009426205315937.gif",
        "[\u53f3\u592a\u6781]": "2009426205315143.gif"
    };
    return function(b, myClass) {
        var d = "/static/home/images/emoji/qq/";
        if(b){
            if(myClass){
                return b.replace(/\/:[^\/]{0,8}/g,
                    function(b) {
                        for (var e = b.length; 2 < e; e--){
                            if (b.substr(0, e) in a)
                                return '<img class="' + myClass + '" src="' + d + a[b.substr(0, e)] + '"/>' + b.substr(e);
                        }
                        return b
                    })
            }else{
                return  b in a && d + a[b]
            }
        }else{
            return {
                emotions: a,
                baseUrl: d
            }
        }
    }
} ()

//输入某个表情key  得到对应的地址
var mb = function() {
    return function(a) {
        var b = ba().emotions,
            u = ba().baseUrl,
            d = Object.keys(b);
        var getImg = function(url){
            return '<img class="emoji" src="'+u+url+'">'
        }
        return a.replace(/\[[NOK\u4E00-\u9FA5\uF900-\uFA2D]{1,3}\]/g,
            function(a) {
                for (var e = a.length; 2 < e; e--) if (a.substr(0, e) in b) {
                    var g = a.substr(0, e),
                        k = d.indexOf(g);
                    return k!=-1 ? getImg(b[g]) : xss(a);
                }
                return xss(a)
            })
    }
} ();

//生成随机msg_id
function genID(length){
    return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36);
}
//渲染所有的表情
var drawEmoji = function (){
    //如果没渲染图片
    if (!$("#emojiPnl").children().length) {
        var a = ba(),
            c = a.baseUrl,
            d = document.createDocumentFragment(),
            a = a.emotions,
            e;
        for (e in a) {
            var f = new Image;
            f.className = "emoji-item";
            f.src = c + a[e];
            $.attr(f, "key", e);
            d.appendChild(f)
        }
        $("#emojiPnl").append(d)
    }
    // $("#pnlExt").removeClass("hide");
    // $("#emojiPnl").toggleClass("hide")
}

//没有更多了
var notMessage = function() {
    $("#histStart").html('没有更多了');
    setTimeout(function() {
            var day2 = new Date();
            day2.setTime(day2.getTime());
            var s2 = day2.getHours()+":" + day2.getMinutes() ;// + ":" + day2.getSeconds()
            $("#histStart").html('今天 '+s2);
            // $("#histStart")[0].innerHTML = $.fTime(a, "smart hh:mm:ss")
        },1500)
}



//监听输入框变化
function textKeyDown(){
    if(!isPhone())return ;
    if(vDom.inputMsg.length>0){
        $('#menuBtn').hide()
        $('#sendBtn').show()
    }else{
        $('#menuBtn').show()
        $('#sendBtn').hide()
    }
}

function addText(str){
    $("#text").val($("#text")[0].value + str)
    //更新按钮方式
    isPhone() && textKeyDown()
}

//点击发送按钮
function sandBtn(msg){
    msg = msg || $('#text').val()
    //调用发送方法
    outputMessage({
        msg_id:genID(10),
        user_head:'https://img2.baidu.com/it/u=1077360284,2857506492&fm=26&fmt=auto&gp=0.jpg',
        user_id:2,
        msg_type:1,
        nickname:'兔白白',
        stime:123445,
        msg:msg
    })

    //清空输入框
    $('#text').val('')

    //如果是手机模式  更新按钮状态
    isPhone() && textKeyDown()

    //隐藏 表情 and 问题

}

function clickMenu(){
        $('#pnlBtns').toggleClass('show')
        if($('#pnlBtns').is('.show')){
            $('#menuBtn').parents('.pnl-text').height('9.2rem')
            $('#show').height('27rem')
            //隐藏问题
            $('#quesPnl').addClass('hide')
        }else{
            $('#menuBtn').parents('.pnl-text').height('3.2rem')
            $('#show').removeAttr('style')
        }
        scrollTop()
}

//移动滚动条
function scrollTop(){
    var div = document.getElementById('show');
    // console.log(div,'---div')
    if(!div)return;
    div.scrollTop = div.scrollHeight;
}

/**
 * 输出消息内容
 * @param message
 *      msg_id  消息id
 *      msg_type 消息类型
 *      nickname 消息人名字
 *      stime 消息发送时间
 *      message  消息主体内容
 */
var outputMessage = function (message){
    if(message.user_id == 1){
        message.about = 1 //左
    }else{
        message.about = 2 //右
    }
    //表情替换
    message.msg = filterXSS(mb(message.msg));
    $('#msgs').append(template('Message-box',{data:message}))
    var obj = $('.msg-res[data-ack="' + message.msg_id + '"]')
    obj.addClass('sending').attr("title", '消息发送中...');
    setTimeout(function(){
        //  sending 消息发送中  resend  消息发送失败
        obj.removeClass('sending').addClass('resend').attr("title", '消息发送失败，请点击重发');
    },1500)

    //滚动条保持在底部
    scrollTop()
}

/**
 * 检测图片是否存在
 * @param url
 */
let imageIsExist = function(url) {
    return new Promise((resolve) => {
        var img = new Image();
        img.onload = function () {
            if (this.complete == true){
                resolve(true);
                img = null;
            }
        }
        img.onerror = function () {
            resolve(false);
            img = null;
        }
        img.src = url;
    })
}



/**
 * $touch 需要移动放缩的img
 * $touchOriginal 控制移动放缩的区域
 **/
function touchScale ($touch, $touchOriginal) {
    var sX, eX, sY, eY, scale, x1, x2, y1, y2, imgLeft, imgTop, imgWidth, imgHeight, one = false;
    var originalWidth = $touch.width();
    var originalHeight = $touch.height();
    var imgLeft = parseInt($touch.css('left'));
    var imgTop = parseInt($touch.css('top'));

    $touchOriginal.on('touchstart touchmove touchend', function (event) {
        var touch1 = event.originalEvent.targetTouches[0];  // 第一根手指touch事件
        var touch2 = event.originalEvent.targetTouches[1];  // 第二根手指touch事件
        var fingers = event.originalEvent.touches.length;  // 屏幕上手指数量

        // 手指放在屏幕上的时候
        if (event.type == 'touchstart') {
            if (fingers == 2) {
                // 放缩图片x轴初始
                sX = Math.abs(touch1.pageX - touch2.pageX);
                sY = Math.abs(touch1.pageY - touch2.pageY);
                one = false;
            } else {
                x1 = touch1.pageX;
                y1 = touch1.pageY;
                one = true
            }
        } else if (event.type == 'touchmove') {
            // 手指移动过程
            if (fingers == 2) {
                // 放缩图片x轴
                eX = Math.abs(touch1.pageX - touch2.pageX);
                eY = Math.abs(touch1.pageY - touch2.pageY);
                // 为了放缩更加便捷，取最大的绝对值
                scale = Math.abs(eX - sX) > Math.abs(eY - sY) ? eX - sX : eY - sY;
                $touch.css({
                    'width': originalWidth + scale,
                    'height': originalHeight + scale
                })
            } else if (one) {
                // 错位控制,放缩未结束不允许移动位置
                x2 = touch1.pageX;
                y2 = touch1.pageY;
                $touch.css({
                    'top': imgTop + y2 - y1,
                    'left': imgLeft + x2 - x1
                })
            }
        } else if (event.type == 'touchend') {
            // 放缩结束
            originalWidth = $touch.width();
            originalHeight = $touch.height();
            imgLeft = parseInt($touch.css('left'));
            imgTop = parseInt($touch.css('top'));
        }
    });
}


/**
 * 时间戳转格式时间
 * @param timespan
 * @returns {string}
 */
function formatMsgTime (timespan) {
    var dateTime = new Date(timespan) // 将传进来的字符串或者毫秒转为标准时间
    var year = dateTime.getFullYear()
    var month = dateTime.getMonth() + 1
    var day = dateTime.getDate()
    var hour = dateTime.getHours()
    var minute = dateTime.getMinutes()
    // var second = dateTime.getSeconds()
    var millisecond = dateTime.getTime() // 将当前编辑的时间转换为毫秒
    var now = new Date() // 获取本机当前的时间
    var nowNew = now.getTime() // 将本机的时间转换为毫秒
    var milliseconds = 0
    var timeSpanStr
    milliseconds = nowNew - millisecond
    if (milliseconds <= 1000 * 60 * 1) { // 小于一分钟展示为刚刚
        timeSpanStr = '刚刚'
    } else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) { // 大于一分钟小于一小时展示为分钟
        timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前'
    } else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) { // 大于一小时小于一天展示为小时
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前'
    } else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) { // 大于一天小于十五天展示位天
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前'
    } else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year === now.getFullYear()) {
        // timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute
        timeSpanStr = month + '月' + day + '日'
    } else {
        timeSpanStr = year + '年' + month + '月' + day + '日'
    }
    return timeSpanStr
}

function formatMsgTime2 (timespan) {
    var dateTime = new Date(timespan) // 将传进来的字符串或者毫秒转为标准时间
    var year = dateTime.getFullYear()
    var month = dateTime.getMonth() + 1
    var day = dateTime.getDate()
    var hour = dateTime.getHours()
    var minute = dateTime.getMinutes()
    // var second = dateTime.getSeconds()
    var millisecond = dateTime.getTime() // 将当前编辑的时间转换为毫秒
    var now = new Date() // 获取本机当前的时间
    var nowNew = now.getTime() // 将本机的时间转换为毫秒
    var milliseconds = 0
    var timeSpanStr
    milliseconds = Math.round((nowNew - millisecond)/1000)
    if ( milliseconds <=  60 * 60 * 24) { // 大于一小时小于一天展示为小时
        timeSpanStr = '今天 '+ hour + ':' + minute
    } else if ( milliseconds <=  60 * 60 * 24 * 3) {
        timeSpanStr = Math.round(millisecond/(60*60*24))==1 ? ('昨天 '+ hour + ':' + minute) : ('前天 '+ hour + ':' + minute)
        // timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前'
    } else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year === now.getFullYear()) {
        // timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute
        timeSpanStr = month + '月' + day + '日'
    } else {
        timeSpanStr = year + '年' + month + '月' + day + '日'
    }
    return timeSpanStr
}


function flash_title(){
    var flash = {
        step:0,
        old_title:document.title,//原始标题
    }

    //启动闪动
    var run = function(){
        // console.log(flash.step,'---flash.step')
        flash.step++
        if (flash.step == 3) { flash.step = 1 }
        if (flash.step == 1) { document.title = "[请尽快处理]有新的任务"; }
        if (flash.step == 2) { document.title = "            有新的任务"; }
        if(flash.step) {
            setTimeout(()=>{
                run()
            }, 1000);
        }
    }

    flash.start = function(){
        if(flash.step>0) return;
        flash.step = 0
        run()
    }

    //停止
    flash.close = function(){
        flash.step = -1
        document.title = flash.old_title
    }
    return flash;
}